package com.bitcola.security.activity.biz;


import com.bitcola.security.activity.constant.PrizeConstant;
import com.bitcola.security.activity.feign.IDataServiceFeign;
import com.bitcola.security.activity.mapper.BalanceChangeLogMapper;
import com.bitcola.security.activity.mapper.ColaUserMapper;
import com.bitcola.security.common.constant.BalanceTypeConstants;
import com.bitcola.security.common.util.Snowflake;
import com.bitcola.entity.BalanceChange;
import com.bitcola.entity.ColaUserEntity;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class BalanceChangeBiz {
    Snowflake snowflake=new Snowflake(2,11);
    @Resource
    IDataServiceFeign iDataServiceFeign;
    @Autowired
    BalanceChangeLogMapper balanceChangeLogMapper;
    @Autowired
    ColaUserMapper userMapper;

    public BalanceChange createChange(String userId, String source, String descr, BigDecimal amount,String type,String coinCode){
        BalanceChange balanceChange=new BalanceChange();
        balanceChange.setId(snowflake.nextIdStr());
        balanceChange.setUserId(userId);
        balanceChange.setCreateTime(new Date());
        balanceChange.setSource(source);
        balanceChange.setType(type);
        balanceChange.setDescription(descr);
        balanceChange.setAmount(amount);
        balanceChange.setCoinCode(coinCode);
        balanceChangeLogMapper.insert(balanceChange);

        return balanceChange;
    }


     public List<BalanceChange>queryPrize(String userId,String  status,int page,int size ) {


        Example example = new Example(BalanceChange.class);

        if(!StringUtils.isEmpty(status)){
            if(status.equals("all")){
                example.or().andEqualTo("userId",userId).andEqualTo("source", BalanceTypeConstants.prize_balance_frozen);
            }else if(status.equals("gain")){
                example.createCriteria().andEqualTo("userId",userId).andEqualTo("source", BalanceTypeConstants.prize_balance_frozen).andGreaterThan("amount",0);
            }else{
                example.createCriteria().andEqualTo("userId",userId).andEqualTo("source", BalanceTypeConstants.prize_balance_frozen).andLessThan("amount",0);

            }

        }
        RowBounds rowBounds=new RowBounds((page-1)*size,size);
        return balanceChangeLogMapper.selectByExampleAndRowBounds(example,rowBounds);



    }


    public BigDecimal staticsRedPack(){
        var value= balanceChangeLogMapper.statics(PrizeConstant.RED_PACK).add(iDataServiceFeign.getConfig("red_pack_show_amount")==null?BigDecimal.ZERO:new  BigDecimal(iDataServiceFeign.getConfig("red_pack_show_amount")));
        return value==null?BigDecimal.ZERO:value;
    }
    public static Map<String, Object> objectToMap(Object obj) {
        if (obj == null) {
            return null;
        }

        Map<String, Object> map = new HashMap<String, Object>();
        try {
            Field[] declaredFields = obj.getClass().getDeclaredFields();
            for (Field field : declaredFields) {
                field.setAccessible(true);
                map.put(field.getName(), field.get(obj));
            }
        } catch (Exception e) {

        }

        return map;
    }

   public List<Map<String,Object>>queryLast(int size)
   {


       Example example=new Example(BalanceChange.class);
       example.createCriteria().andEqualTo("description",PrizeConstant.RED_PACK);
       example.orderBy("createTime").desc();
       var result=new ArrayList<Map<String,Object>>();
       var list=balanceChangeLogMapper.selectByExampleAndRowBounds(example,new RowBounds(0,size));
       for(BalanceChange balanceChange:list){
           var map=objectToMap(balanceChange);
            ColaUserEntity colaUserEntity= userMapper.info(balanceChange.getUserId());
            if(colaUserEntity==null) continue;
           map.put("userName",colaUserEntity.getUsername());
           map.put("icon",colaUserEntity.getAvatar());
           result.add(map);

       }

       return result;


   }

   public List<Map<String,Object>>query(String userId,int page,int size)
   {
       Example example=new Example(BalanceChange.class);
       example.createCriteria().andEqualTo("userId",userId);
       example.orderBy("id").desc();
       var list=balanceChangeLogMapper.selectByExampleAndRowBounds(example,new RowBounds((page-1)*size,size));
      var ys= list.stream().map(BalanceChangeBiz::objectToMap).collect(Collectors.toList());
      ys.forEach(y->{
          y.put("time",y.get("createTime"));
          y.put("number",y.get("amount"));
      });
      return ys;


   }



}
